﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using ZXing;

namespace 条形码生成与识别
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 条形码生成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            string text = textBox1.Text;
            CreatBar(text,pictureBox1);
        }
        /// <summary>
        /// 保存条形码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            string fileNmae = Directory.GetCurrentDirectory() + @"\img\" + textBox1.Text + ".jpg";
            if (pictureBox1.Image != null)
            {
                if (File.Exists(fileNmae))
                {
                    label1.ForeColor = Color.Blue;
                    label1.Text = "编码已存在！";
                }
                else
                {
                    pictureBox1.Image.Save(fileNmae);
                    label1.ForeColor = Color.Blue;
                    label1.Text = "保存成功！";
                }
            }
        }
        /// <summary>
        /// 条形码识别
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            //创建识别器
            BarcodeReader reader = new BarcodeReader();
            try
            {
                using (Bitmap img = new Bitmap(pictureBox2.Image))
                {
                    try
                    {
                        Result result = reader.Decode(img);
                        reader.Options.CharacterSet = "UTF-8";
                        label3.Text = result.Text == null ? "" : result.Text;
                        string num = "";
                        label4.Text = "";
                        for (int i = 0; i < 3; i++)
                            num += Code.ConvertToIntArray(label3.Text)[i];

                        label4.ForeColor = Color.Black;
                        label4.Text = Code.GetCountry(Convert.ToInt32(num));
                    }
                    catch
                    {
                        label4.ForeColor = Color.Orange;
                        label4.Text = "识别失败！";
                    }
                }
            }
            catch (Exception ex)
            {
                label3.ForeColor = Color.Red;
                label3.Text = ex.Message;
            }
        }
        /// <summary>
        /// 打开图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                Bitmap img = new Bitmap(ofd.FileName);
                pictureBox2.Image = img;
            }
        }
        /// <summary>
        /// 随机生成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click(object sender, EventArgs e)
        {
            string str = "";
            Random random = new Random();
            for (int i = 0; i < 12; i++)
            {
                str += random.Next(0, 10);
            }
            textBox1.Text = str;
          
            CreatBar(str, pictureBox1);
            ValidInput(str);
        }
        /// <summary>
        /// 创建条形码
        /// </summary>
        /// <param name="text"></param>
        /// <param name="pictureBox"></param>
        private void CreatBar(string text,PictureBox pictureBox)
        {
            Code code = new Code();
            //二进制编码字符串
            string bitCode = "";
            try
            {
                label1.ForeColor = Color.Red;
                //输入验证
                ValidInput(text);
                //校验位
                string checkBit = code.GetCheckBit(text).ToString();
                textBox2.Text = checkBit;
                bitCode = GetCodeString(text + checkBit);
                label1.ForeColor = Color.Green;
                label1.Text = "生成成功";
                //绘制条形码
                pictureBox.Image = code.DrawCode(text, bitCode, 10, 600).Bitmap;
            }
            catch (Exception ex)
            {
                label1.Text = ex.Message;
            }
        }
        /// <summary>
        /// 获取二进制编码字符串
        /// </summary>
        /// <param name="str">十进制编码字符串</param>
        /// <returns>二进制编码字符串</returns>
        private string GetCodeString(string text)
        {
            Code code = new Code();
            int[] num = Code.ConvertToIntArray(text + code.GetCheckBit(text));
            int prefix = num[0];
            string codeStr = "101";//起始位101
            //左侧数据编码
            for (int i = 0; i < 6; i++)
            {
                //获取编码方式
                int codeType = code.GetCodeChose(num[0])[i];
                //获取字符编码
                byte[] tempB = code.GetCode(codeType, num[i+1]);
                string tempS = "";
                for (int j = 0; j < tempB.Length; j++)
                    tempS += tempB[j];
                codeStr += tempS;
            }
            codeStr += "01010";//分隔位01010
            //右侧数据编码
            for (int i = 0; i < 6; i++)
            {
                //获取字符编码，右侧按C方式编码
                byte[] tempB = code.GetCode(2, num[i + 7]);
                string tempS = "";
                for (int j = 0; j < tempB.Length; j++)
                    tempS += tempB[j];
                codeStr += tempS ;
            }
            codeStr += "101";//终止位101
            return codeStr;
        }
        /// <summary>
        /// 输入格式验证
        /// </summary>
        /// <param name="str"></param>
        private void ValidInput(string str)
        {
            if (str.Length != 12)
                throw new Exception("编码长度不正确，长度为12!");
            string num = "";
            for (int i = 0; i < 3; i++)
                num += Code.ConvertToIntArray(str)[i];
            try
            {
                Code.GetCountry(Convert.ToInt32(num));
            }
            catch(Exception ex)
            {
                label1.ForeColor = Color.Orange;
                label1.Text =  ex.Message;
            }
            
        }
    }
}
